package com.yizisu.basemvvm.mvvm


import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.yizisu.basemvvm.mvvm.mvvm_helper.BaseMvvmInterface
import com.yizisu.basemvvm.mvvm.mvvm_helper.LiveBean
import com.yizisu.basemvvm.mvvm.mvvm_helper.MessageBus
import com.yizisu.basemvvm.mvvm.mvvm_helper.*
import com.yizisu.basemvvm.utils.notchlib.NotchScreenManager

/**
 * 若红楼梦空，亦初心不变
 * 作者：kotle
 * 包名：com.yizisu.basemvvm.mvvm
 * 时间：2019/1/17 22:47
 * 描述：
 */
abstract class MvvmActivity : AppCompatActivity(), BaseMvvmInterface {
    /**
     * 动态权限请求码，随意
     */
    private val needPermissionCode = 1452
    /**
     * 动态权限的回调，是否有此权限
     */
    private var needPermissionCall: Function1<Boolean, Unit>? = null

    /**
     * 创建其他格式的viewModel
     */
    inline fun <reified P : MvvmViewModel> getViewModel(): P {
        return ViewModelProvider(this).get(P::class.java)
    }

    /**
     * 是否需要屏幕适配
     */
    open fun isNeedScreenAdaptation() = true

    /**
     * 是否全屏
     */
    open fun isFullScreen() = false

    /**
     * 是否支持滑动返回
     */
    open fun isCanSwipeBack() = false

    /**
     * onCreate
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        //是否全屏
        if (isFullScreen()) {
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            NotchScreenManager.getInstance().setDisplayInNotch(this)
        }
        super.onCreate(savedInstanceState)
        when (val contentView = getLayoutResOrView(layoutInflater)) {
            is Int -> {
                setContentView(contentView)
            }
            is View -> {
                setContentView(contentView)
            }
            null -> {
                //什么都不做
            }
            else -> {
                throw IllegalArgumentException("getLayoutResOrView() only return view/LayoutRes")
            }
        }
        initUi(savedInstanceState)
        getClickView()?.forEach {
            it?.setOnClickListener(this)
        }
        initViewModel()
        initData()
        MessageBus.register(this)
    }

    override fun onDestroy() {
        MessageBus.unRegister(this)
        super.onDestroy()
    }

    /**
     * 请求用户权限
     */
    override fun getPermission(
        permission: MutableList<String>,
        needPermissionCall: Function1<Boolean, Unit>
    ) {
        var isNeedRequest = false
        val list = mutableListOf<String>()
        permission.forEach {
            if (ActivityCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED) {
                isNeedRequest = true
                list.add(it)
            }
        }
        if (isNeedRequest) {
            this.needPermissionCall = needPermissionCall
            if (list.isNotEmpty()) {
                ActivityCompat.requestPermissions(this, list.toTypedArray(), needPermissionCode)
            } else {
                needPermissionCall.invoke(true)
            }
        } else {
            needPermissionCall.invoke(true)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
    }

    /**
     * 处理请求的权限结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == needPermissionCode) {
            var isGetAllPermission = true
            grantResults.forEach {
                if (it != PackageManager.PERMISSION_GRANTED) {
                    isGetAllPermission = false
                }
            }
            needPermissionCall?.invoke(isGetAllPermission)
        }
    }

    /**
     * 注册livedata，忽略空的情况
     */
    inline fun <T> LiveBean<T>.register(crossinline observer: (LiveBean<T>) -> Unit): Observer<LiveBeanValue<T>> {
        return registerLiveBean(this@MvvmActivity, observer)
    }

    /**
     * 注册livedata，只处理成功的情况
     */
    inline fun <T> LiveBean<T>.registerOnSuccess(crossinline success: (T) -> Unit): Observer<LiveBeanValue<T>> {
        return registerOnSuccessLiveBean(this@MvvmActivity, success)
    }

    /**
     * 注册livedata，忽略空的情况
     */
    inline fun <T> MediatorLiveBean<T>.register(crossinline observer: (MediatorLiveBean<T>) -> Unit): Observer<LiveBeanValue<T>> {
        return registerLiveBean(this@MvvmActivity, observer)
    }

    /**
     * 注册livedata，只处理成功的情况
     */
    inline fun <T> MediatorLiveBean<T>.registerOnSuccess(crossinline success: (T) -> Unit): Observer<LiveBeanValue<T>> {
        return registerOnSuccessLiveBean(this@MvvmActivity, success)
    }
}